package com.zhdl.websocket.server;

import com.zhdl.websocket.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@Component
//@ServerEndpoint(value = "/custom/{sid}")
@ServerEndpoint(value = "/webSocket/{sid}")
public class WebSocketRunServer {


    public static WebSocketService webSocketService;


    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {

        // WebSocket 连接建立时调用
        log.info("CustomWsServer WebSocket connection opened: {} , 链接的客户端id: {}", session.getId(), sid);

        //保存session对照关系
        webSocketService.saveSessionMap(sid, session);

    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 接收到客户端发送的消息时调用
        log.info("CustomWsServer WebSocket connection onMessage: id: {} Received message: {}", session.getId(), message);
        // 回复消息给客户端
        session.getAsyncRemote().sendText("WebSocket Received: " + message);

    }


    @OnClose
    public void onClose(Session session, CloseReason closeReason, @PathParam("sid") String sid) {

        //删除离线用户
        webSocketService.deleteSessionMap(sid);
        //客户端关闭时调用
        log.info("CustomWsServer WebSocket connection onClose: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        //客户端异常时调用
        log.error("CustomWsServer ws : onError id: {} throwable : [{}]", session.getId(), throwable.getMessage());
    }

}
